package com.kaifamiao.jsp.servlet;

import com.kaifamiao.jsp.entity.Customer;
import com.kaifamiao.utils.JdbcHelper;
import com.kaifamiao.utils.RowHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.logging.Logger;

@WebServlet( "/customer/sign/in" )
public class CustomerSignInServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void doPost(HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        final String signUpURL = request.getContextPath() + "/sign-in.jsp" ;
        // 如果校验失败
        if( !this.validate(request) ){
            response.sendRedirect( signUpURL );
            return ;
        }

        String username = request.getParameter( "username" );
        String password = request.getParameter( "password" );

        JdbcHelper helper = JdbcHelper.getInstance();

        String sql = "SELECT id , username , password , nickname , name , gender , birthdate " +
                     "FROM t_customers " +
                     "WHERE username = ? " ;

        RowHandler<Customer> handler = new RowHandler<Customer>() {
            @Override
            public Customer handle(ResultSet rs) throws SQLException {
                Customer c = new Customer();
                c.setId( rs.getInt( "id" ) );
                c.setUsername( rs.getString( "username" ) );
                c.setPassword( rs.getString( "password" ) );
                c.setNickname( rs.getString( "nickname" ) );
                c.setName( rs.getString( "name" ) );
                c.setGender( rs.getString( "gender" ) );
                java.sql.Date date = rs.getDate( "birthdate" );
                LocalDate birthdate = date.toLocalDate();
                c.setBirthdate( birthdate );
                return c;
            }
        };

        Customer c = helper.single( sql , handler , username );

        helper.release();

        if( c == null ) {
            session.setAttribute( "message" , "用户名不存在" );
            response.sendRedirect( signUpURL );
            return ;
        }

        if( !password.equals( c.getPassword() ) ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "密码错误" );
            response.sendRedirect( signUpURL );
            return ;
        }

        // 将用户对象添加到 session 的属性中
        session.setAttribute( "customer" , c );
        response.sendRedirect( request.getContextPath() + "/customer/list" );
    }

    /**
     * 对请求参数进行数据校验，以确保数据有效
     * @param request 表示请求对象
     * @return 当所有请求参数都通过检验时返回 true
     */
    private boolean validate(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = request.getParameter( "username" );
        if( username == null || username.trim().isEmpty() ) {
            session.setAttribute( "message" , "用户名不能为空" );
            return false ;
        }
        String password = request.getParameter( "password" );
        if( password == null || password.trim().isEmpty() ) {
            session.setAttribute( "username" , username );
            session.setAttribute( "message" , "密码不能为空" );
            return false ;
        }
        return true ;
    }

}
